/**
 * 访问明细
 *
 * @format
 */

import { BaseDao } from '../../sdk'
import { getToday } from '../../utils'
import { ACCESS_DB_NAME, JOIN_DB_NAME } from '../../db'

export default class UserAccessService {
  context: IContext<IParams>
  accessdao: IBaseDao
  joindao: IBaseDao
  constructor(context: IContext<IParams>) {
    this.context = context
    this.accessdao = new BaseDao(context, ACCESS_DB_NAME)
    this.joindao = new BaseDao(context, JOIN_DB_NAME)
  }
  /**
   * 增加访问记录
   * @param {是否关注店铺} isFollow
   */
  async addAccess(userInfo: IUserInfo, vipInfo: IVipInfo) {
    let { openId, data } = this.context
    let { activityId, userNick, avatar, inviteId } = data
    const joinInfo = await this.joindao.findOne({ activityId, openId })

    const today = getToday()
    await this.accessdao.insertOne({
      openId,
      activityId,
      userNick,
      avatar,
      isReceiveShare: !!inviteId,
      inviteId,
      isJoin: joinInfo ? true : false,
      isVip: vipInfo.isVip,
      follow: userInfo.follow,
      member: userInfo.member,
      accessTime: Date.now(),
      createTime: Date.now(),
      updateTime: Date.now(),
      createDay: today
    })
    const firstLoginToday = userInfo?.login?.[today] === 1

    return { openId, firstLoginToday, newUser: userInfo.createDay === today && firstLoginToday }
  }

  async getAccessCount() {
    let { openId, data } = this.context
    let { activityId } = data
    return await this.accessdao.count({
      openId,
      activityId
    })
  }
}
